package com.yj.easydialog.dialog;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import java.lang.ref.WeakReference;

/**
 * Created by Sigthp-P-Department on 2018/4/4.
 */

class DialogViewHelper {

    private View mContentView=null;
    private SparseArray<WeakReference<View>> mViews;
    private TextView view;

    public DialogViewHelper(Context mContext, int mViewLayoutResId) {
        this();
        mContentView = LayoutInflater.from(mContext).inflate(mViewLayoutResId, null);
    }

    public DialogViewHelper() {
        mViews=new SparseArray<>();
    }

    public void setContentView(View contentView) {
        this.mContentView = contentView;
    }

    public View getContentView() {
        return mContentView;
    }

    public void setTextView(int viewId, CharSequence charSequence) {
        TextView tv = getView(viewId);
        if (tv != null) {
            tv.setText(charSequence);
        }
    }

    public void setOnClickLisner(int viewId, View.OnClickListener onClickListener) {
        View view = getView(viewId);
        if(view!=null){
            view.setOnClickListener(onClickListener);
        }
    }

    public <T extends View>T getView(int viewId) {
        WeakReference<View> weakReference = mViews.get(viewId);

        View view = null;
        if(weakReference!=null){
            view = weakReference.get();
        }
        if(view==null){
            view = mContentView.findViewById(viewId);
            if(view!=null){
                mViews.put(viewId,new WeakReference<>(view));
            }
        }
        return (T) view;
    }
}
